package moltencore.network.protocol;

import java.nio.ByteBuffer;

import moltencore.game.Player;

public class PlayerData {
	private long clientId;
	private static final int CLIENT_ID_LENGTH = Long.SIZE / 8;
	private byte bubbleSetId;
	private static final int BUBBLE_SET_ID_LENGTH = Byte.SIZE / 8;
	private byte nameLength;
	private static final int NAME_LENGTH_LENGTH = Byte.SIZE / 8;
	private byte[] name;

	public static final int SIZE =
			CLIENT_ID_LENGTH +
			BUBBLE_SET_ID_LENGTH +
			NAME_LENGTH_LENGTH;

	public PlayerData() {
	}

	public PlayerData(Player player) {
		this.clientId = player.getClientId();
		this.bubbleSetId = player.getBubbleSetId();
		this.name = player.getName().getBytes();
		this.nameLength = (byte)name.length;
	}

	public long getClientId() {
		return clientId;
	}

	public byte getBubbleSetId() {
		return bubbleSetId;
	}

	public String getName() {
		return new String(name);
	}

	public void getBytes(byte[] buffer, int offset) {
		ByteBuffer bb = ByteBuffer.wrap(buffer, offset, buffer.length - offset);
		bb.putLong(clientId);
		bb.put(bubbleSetId);
		bb.put(nameLength);
		if(nameLength > 0) {
			bb.put(name);
		}
	}

	public void fill(byte[] buffer, int offset) {
		ByteBuffer bb = ByteBuffer.wrap(buffer, offset, buffer.length - offset);
		clientId = bb.getLong();
		bubbleSetId = bb.get();
		nameLength = bb.get();
		name = new byte[nameLength];
		bb.get(name);
	}

	public int getSize() {
		return SIZE + name.length;
	}

	@Override
	public boolean equals(Object o) {
		if(this == o) return true;
		if(o == null || getClass() != o.getClass()) return false;

		PlayerData that = (PlayerData) o;

		if(clientId != that.clientId) return false;

		return true;
	}

	@Override
	public int hashCode() {
		return (int) (clientId ^ (clientId >>> 32));
	}
}